<?php

declare(strict_types=1);

namespace app\controller;

use core\Controller;
use core\Request;
use app\model\User;

class HomeController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
        // Optionally add route-specific middleware
        // This would typically be done in a route definition, but shown here for example
        // e.g., $router->middleware(\App\Middleware\AuthMiddleware::class);
    }

    public function index(): void
    {
        if ($this->request->getMethod() === 'POST') {
            if (!$this->request->validateCsrfToken($this->request->post('_csrf'))) {
                $this->json(['error' => 'Invalid CSRF token'], 403);
            }
            // Example validation
            $errors = $this->request->validate([
                'email' => ['required' => true, 'type' => 'email'],
                'id'    => ['required' => true, 'type' => 'int'],
            ]);
            if ($errors) {
                $this->json(['errors' => $errors], 422);
            }
        }

        $model = new User();
        $this->view('home/index', [
            'data' => $model->getData(),
            'csrf' => $this->request->generateCsrfToken(),
        ]);
    }
}